package com.laxcen.basiclib.core.task;


import com.laxcen.basiclib.core.task.core.thread.ThreadPoolManager;

/**
 * thread封装类，功能和@ThreadPoolManager相同
 *  这个用来处理可管控的线程
 */
public class ThreadManager {

    private Runnable command;
    private int delayTime;
    private String tag;
    private String groupName;
    private int priority;

    private ThreadManager() {
    }

    /**
     * 执行任务
     */
    public void execute() {
        ThreadPoolManager.execute(groupName, command, tag, delayTime, priority);
    }

    /**
     *通过tag移除所有线程池组消息(tag值必须有)
     */
    public void removeAllByTag() {
        ThreadPoolManager.removeAllByTag(tag);
    }

    /**
     *移除指定线程池组中的指定的tag（线程池组和Tag必须存在）
     */
    public void removeAllByGroupNameAndTag() {
        ThreadPoolManager.removeMessages(groupName, tag);
    }

    /**
     * 移除指定线程池组中的所有的消息(线程池组必须存在)
     */
    public void removeCallbacksAndMessagesByGrouname() {
        ThreadPoolManager.removeCallbacksAndMessages(groupName);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static class Builder {
        private Runnable command;
        private int delayTime;
        private String tag;
        private String groupName;
        private int priority;

        private Builder() {

        }

        /**
         * 任务延迟时间
         * @param delayTime
         * @return
         */
        public Builder delayTime(int delayTime) {
            this.delayTime = delayTime;
            return this;
        }

        /**
         * 执行任务
         * @param command
         * @return
         */
        public Builder command(Runnable command) {
            this.command = command;
            return this;
        }

        /**
         * 任务tag
         * @param tag
         * @return
         */
        public Builder tag(String tag) {
            this.tag = tag;
            return this;
        }

        /**
         * 任务存在的线程池组
         * @param groupName
         * @return
         */
        public Builder groupName(String groupName) {
            this.groupName = groupName;
            return this;
        }

        /**
         * 任务优先级
         * {@link ThreadPriority#MAX_PRIORITY} {@link ThreadPriority#MIN_PRIORITY} {@link ThreadPriority#NORM_PRIORITY}
         * @param priority
         * @return
         */
        public Builder priority(int priority) {
            this.priority = priority;
            return this;
        }

        public ThreadManager build() {
            ThreadManager threadManager = new ThreadManager();
            threadManager.command = command;
            threadManager.tag = tag;
            threadManager.delayTime = delayTime;
            threadManager.groupName = groupName;
            threadManager.priority = priority;
            return threadManager;
        }
    }
}
